package tedexis.mercurio.transformers;

import gurulab.maya.common.PhoneAddress;
import gurulab.merlin.core.envelope.Envelope;
import gurulab.merlin.core.router.EnvelopeTransformer;

public class MetromovilTransformer implements EnvelopeTransformer {

	private final String PEER = "metromovil";
	private final String AREA_CODE_MOVISTAR_GSM		= "593";
	private final String AREA_CODE_MOVISTAR_CDMA_1	= "074";
	private final String AREA_CODE_MOVISTAR_CDMA_2	= "075";
	private final String AREA_CODE_PORTA_GSM		= "593";
	
	private final String COUNTRY_CODE_ECUADOR		= "593";
		
	/*
	 * Movistar (GSM) 593
	 * Movistar (CDMA) 074
	 * Movistar (CDMA) 075
	 * Porta (GSM) 593
	 * 
	 * Ejemplos
	 * 59393978884
	 * 59384578523
	 * 0749565865
	 * 0757855854
	 */
	
	public void transform(Envelope envelope) {
		
		if (envelope.getDestinationRoute()!=null && envelope.getDestinationRoute().getPeer().equalsIgnoreCase(PEER)) {
			//Va hacia la operadora
			//Transformacion del SMPPOperator

			try{
				//Va hacia la operadora
				//Transformacion del SMPPOperator
				PhoneAddress phoneAdd = (PhoneAddress)envelope.getDestination ();
				phoneAdd.setCrude (false);
				phoneAdd.setSchema("phone");

				//Con codigo de pais
				//phoneAdd.setNumber (COUNTRY_CODE_ECUADOR+phoneAdd.getAreaCode()+phoneAdd.getLocal());
				//Sin codigo de pais
				phoneAdd.setNumber (phoneAdd.getAreaCode()+phoneAdd.getLocal());
				envelope.setDestination (phoneAdd);			
			}catch(Exception exc){
				exc.printStackTrace();
			}
		} 
		
		if (envelope.getOriginRoute()!=null && envelope.getOriginRoute().getPeer().equalsIgnoreCase(PEER)) {
			//Recibe de la operadora
			//Transformacion del SmppEP
			
			PhoneAddress srcPhone = null; 
			String number = null;			

			number = ((PhoneAddress) envelope.getOrigin()).getNumber();
			//Se construye un nuevo objeto PhoneAddress (Origin) tomando como base 
			//la propiedad number del envelope.getOrigin() del objeto PhoneAddress original
			try {				

				//Sin codigo de pais
				String codigoArea = number.substring(0, 3);				
				srcPhone = new PhoneAddress(COUNTRY_CODE_ECUADOR, codigoArea, number.substring(4));
				
				//Con codigo de pais
				//String codigoArea = number.substring(3, 6);				
				//srcPhone = new PhoneAddress(COUNTRY_CODE_ECUADOR, codigoArea, number.substring(7));

				srcPhone.setCrude(false);
				envelope.setOrigin(srcPhone);
			}catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
